package com.hexus.eve.utils;

import java.util.Date;
import java.util.HashSet;
import javax.annotation.PostConstruct;

import org.apache.log4j.Logger;
import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hexus.eve.entities.Type;

/**
 * Spring singletone bean which contains set of all blueprints' IDs 
 * and provide all functionality required regarding blueprints
 * 
 * @author Mikhail_Berastau 
 */
@SuppressWarnings("restriction")
@Service
public class BlueprintUtils {
	private Logger log = Logger.getLogger(this.getClass());
	
	@Autowired
	private SessionFactory sessionFactory;
	
	private static BlueprintUtils instance;
	
	/**
	 * Contains set of all blueprints' IDs. Used for the isBlueprint functionality.
	 */
	private static HashSet<Integer> blueprintsIDs = new HashSet<Integer>();
	
	private BlueprintUtils(){
		instance = this;
	}
	
	public static BlueprintUtils getInstance() {
		return instance;
	}
	
	@SuppressWarnings({ "unused", "unchecked" })
	@PostConstruct
	private void init() {
		Date timer = new Date();
		
		if(log.isDebugEnabled()) {
			log.debug("Initializing Blueprints bean...");
		}
		
		Session session = sessionFactory.openSession();
		try {
			//Getting all blueprints' IDs (used for isBlueprint functionality)
			Query sqlQuery = session.createSQLQuery("select blueprintTypeID from invBlueprintTypes").addScalar("blueprintTypeID", Hibernate.INTEGER);
			blueprintsIDs.addAll(sqlQuery.list());
		}
		catch(Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
		}
		finally {
			session.close();
		}
		
		if(log.isDebugEnabled()) {
			log.debug("The Blueprints bean is initialized. " + blueprintsIDs.size() + " blueprint IDs are loaded in " + ((new Date()).getTime() - timer.getTime()) / 1000 + " seconds.");
		}

	}

	public Boolean isBlueprint(Integer id) {
		return blueprintsIDs.contains(id);
	}
	
	public Boolean isBlueprint(Type type) {
		return blueprintsIDs.contains(type.getId());
	}

}
